package com.skynet.supervision.utils;

import cn.hutool.core.thread.ThreadException;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.File;
import java.util.ArrayList;
import java.util.List;

@Component
/**
 * 本地文件操作工具类
 */
public class FilesUtils {

    //本地上传文件路径
    @Value("${skynet.profile}")
    public String FILE_LCAL_PATH="";

    //映射路径
    @Value("${skynet.file_mapping_path}")
    public String FILE_MAPPING_PATH="";

    //映射路径前缀
    @Value("${skynet.file_mapping_path_prefix}")
    public String FILE_MAPPING_PATH_PREFIX;

    //本地的后端服务的url，默认先用线上
//    public String headUrl="http://47.94.249.112/api";
//    @Value("${skynet.local.url}")
    public String headUrl="http://192.168.20.130/api";
//    public String headUrl="本地服务器ip/api";

    /**
     * 本地文件上传单个文件
     */
    @SneakyThrows
    public String upload(MultipartFile file){
        //文件不为空
        if(file.isEmpty()){
            throw new ThreadException("上传文件不能为空");
        }
        //真实上传路径是否存在，不存在创建该路径
        File fileRealPath = new File(FILE_LCAL_PATH.replaceAll("file:",""));
        if(!fileRealPath.exists()){
            fileRealPath.mkdirs();
        }
        //开始处理上传文件
        String fileName = file.getOriginalFilename();
        String newFileName =  TimeUtils.currentTime()+"_"+fileName;
        file.transferTo(new File(fileRealPath, newFileName));
        return headUrl+FILE_MAPPING_PATH_PREFIX+newFileName;
    }

    @SneakyThrows
    public static String uploadlocal(MultipartFile file){
        //文件不为空
        if(file.isEmpty()){
            throw new ThreadException("上传文件不能为空");
        }
        //真实上传路径是否存在，不存在创建该路径
        File fileRealPath = new File("/home/skynet/data/");
        if(!fileRealPath.exists()){
            fileRealPath.mkdirs();
        }
        //开始处理上传文件
        String fileName = file.getOriginalFilename();
        String newFileName =  TimeUtils.currentTime()+"_"+fileName;
        file.transferTo(new File(fileRealPath, newFileName));
        return "http://192.168.20.130/api"+"/file/"+newFileName;
    }

    @SneakyThrows
    public List<String> upload(MultipartFile[] file){
        //文件不为空
        if(file==null){
            throw new ThreadException("上传文件不能为空");
        }
        //真实上传路径是否存在，不存在创建该路径
        File fileRealPath = new File(FILE_LCAL_PATH.replaceAll("file:",""));
        if(!fileRealPath.exists()){
            fileRealPath.mkdirs();
        }

        //开始处理上传文件
        List<String> filesUrl = new ArrayList<>();


        for (int i = 0; i <file.length; i++) {
            String fileName = file[i].getOriginalFilename();
            String newFileName =  TimeUtils.currentTime()+"_"+fileName;
            file[i].transferTo(new File(fileRealPath, newFileName));
            filesUrl.add(headUrl+FILE_MAPPING_PATH_PREFIX+newFileName);
        }
        return filesUrl;
    }


    /**
     * 导出ws文件（txt）
     * @param response
     * @param text
     */
    public void exportTxt(HttpServletResponse response, String text){
        response.setCharacterEncoding("utf-8");
        //设置响应的内容类型
        response.setContentType("text/plain");
        //设置文件的名称和格式
        response.addHeader("Content-Disposition","attachment;filename="
                + genAttachmentFileName( "文书", "JSON_FOR_UCC_")//设置名称格式，没有这个中文名称无法显示
                + ".ws");
        BufferedOutputStream buff = null;
        ServletOutputStream outStr = null;
        try {
            outStr = response.getOutputStream();
            buff = new BufferedOutputStream(outStr);
            buff.write(text.getBytes("UTF-8"));
            buff.flush();
            buff.close();
        } catch (Exception e) {
            //LOGGER.error("导出文件文件出错:{}",e);
        } finally {try {
            buff.close();
            outStr.close();
        } catch (Exception e) {
            //LOGGER.error("关闭流对象出错 e:{}",e);
        }
        }
    }

    public  String genAttachmentFileName(String cnName, String defaultName) {
        try {
            cnName = new String(cnName.getBytes("gb2312"), "ISO8859-1");
        } catch (Exception e) {
            cnName = defaultName;
        }
        return cnName;
    }
}
